package co.edu.usbcali.sgi.modelo.control;

import co.edu.usbcali.sgi.dataaccess.dao.MarcaDAO;
import co.edu.usbcali.sgi.dataaccess.daoFactory.XMLHibernateDaoFactory;
import co.edu.usbcali.sgi.dataaccess.sessionFactory.HibernateSessionFactory;
import co.edu.usbcali.sgi.exceptions.*;
import co.edu.usbcali.sgi.modelo.*;
import co.edu.usbcali.sgi.utilities.Utilities;

import java.math.BigDecimal;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;


/**
 * interface MarcaLogic
 * @author Zathura Code Generator http://code.google.com/p/zathura
 *
 */
public class MarcaLogic implements IMarcaLogic {
	public List<Marca> getMarca() throws Exception {
		List<Marca> list = new ArrayList<Marca>();

		try {
			list = XMLHibernateDaoFactory.getInstance().getMarcaDAO().findAll();
		} catch (Exception e) {
			throw new ZMessManager().new GettingException(ZMessManager.ALL +
					"Marca");
		} finally {
		}

		return list;
	}

	public void saveMarca(String marCod, String marNombre,
			String tpvCod_TipoVehiculo) throws Exception {
		Marca entity = null;

		try {
			if (marCod == null) {
				throw new ZMessManager().new EmptyFieldException("marCod");
			}

			if ((marCod != null) &&
					(Utilities.checkWordAndCheckWithlength(marCod, 30) == false)) {
				throw new ZMessManager().new NotValidFormatException("marCod");
			}

			if (marNombre == null) {
				throw new ZMessManager().new EmptyFieldException("marNombre");
			}

			if ((marNombre != null) &&
					(Utilities.checkWordAndCheckWithlength(marNombre, 30) == false)) {
				throw new ZMessManager().new NotValidFormatException(
						"marNombre");
			}

			if (tpvCod_TipoVehiculo == null) {
				throw new ZMessManager().new EmptyFieldException(
						"tpvCod_TipoVehiculo");
			}

			if ((tpvCod_TipoVehiculo != null) &&
					(Utilities.checkWordAndCheckWithlength(
							tpvCod_TipoVehiculo, 30) == false)) {
				throw new ZMessManager().new NotValidFormatException(
						"tpvCod_TipoVehiculo");
			}

			ITipoVehiculoLogic logicTipoVehiculo1 = new TipoVehiculoLogic();
			TipoVehiculo tipoVehiculoClass = logicTipoVehiculo1.getTipoVehiculo(tpvCod_TipoVehiculo);

			if (tipoVehiculoClass == null) {
				throw new ZMessManager().new ForeignException("tipoVehiculo");
			}

			entity = getMarca(marCod);

			if (entity != null) {
				throw new ZMessManager(ZMessManager.ENTITY_WITHSAMEKEY);
			}

			entity = new Marca();
			entity.setMarCod(marCod);
			entity.setMarNombre(marNombre);
			entity.setTipoVehiculo(tipoVehiculoClass);
			HibernateSessionFactory.beginTransaction();
			XMLHibernateDaoFactory.getInstance().getMarcaDAO().save(entity);
			HibernateSessionFactory.commit();
		} catch (Exception e) {
			HibernateSessionFactory.rollback();
			throw e;
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}

	public void deleteMarca(String marCod) throws Exception {
		Marca entity = null;

		if (marCod == null) {
			throw new ZMessManager().new EmptyFieldException("marCod");
		}

		List<Vehiculo> vehiculos = null;
		entity = getMarca(marCod);

		if (entity == null) {
			throw new ZMessManager().new EmptyFieldException("Marca");
		}

		try {
			vehiculos = XMLHibernateDaoFactory.getInstance().getVehiculoDAO()
			.findByProperty("marca.marCod",
					marCod);

			if (Utilities.validationsList(vehiculos) == true) {
				throw new ZMessManager().new DeletingException("vehiculos");
			}

			HibernateSessionFactory.beginTransaction();
			XMLHibernateDaoFactory.getInstance().getMarcaDAO().delete(entity);
			HibernateSessionFactory.commit();
		} catch (Exception e) {
			HibernateSessionFactory.rollback();
			throw e;
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}

	public void updateMarca(String marCod, String marNombre,
			String tpvCod_TipoVehiculo) throws Exception {
		Marca entity = null;

		try {
			if (marCod == null) {
				throw new ZMessManager().new EmptyFieldException("marCod");
			}

			if ((marCod != null) &&
					(Utilities.checkWordAndCheckWithlength(marCod, 30) == false)) {
				throw new ZMessManager().new NotValidFormatException("marCod");
			}

			if (marNombre == null) {
				throw new ZMessManager().new EmptyFieldException("marNombre");
			}

			if ((marNombre != null) &&
					(Utilities.checkWordAndCheckWithlength(marNombre, 30) == false)) {
				throw new ZMessManager().new NotValidFormatException(
						"marNombre");
			}

			if (tpvCod_TipoVehiculo == null) {
				throw new ZMessManager().new EmptyFieldException(
						"tpvCod_TipoVehiculo");
			}

			if ((tpvCod_TipoVehiculo != null) &&
					(Utilities.checkWordAndCheckWithlength(
							tpvCod_TipoVehiculo, 30) == false)) {
				throw new ZMessManager().new NotValidFormatException(
						"tpvCod_TipoVehiculo");
			}

			ITipoVehiculoLogic logicTipoVehiculo1 = new TipoVehiculoLogic();
			TipoVehiculo tipoVehiculoClass = logicTipoVehiculo1.getTipoVehiculo(tpvCod_TipoVehiculo);

			if (tipoVehiculoClass == null) {
				throw new ZMessManager().new ForeignException("tipoVehiculo");
			}

			entity = getMarca(marCod);

			if (entity == null) {
				throw new ZMessManager(ZMessManager.ENTITY_NOENTITYTOUPDATE);
			}

			entity.setMarCod(marCod);
			entity.setMarNombre(marNombre);
			entity.setTipoVehiculo(tipoVehiculoClass);
			HibernateSessionFactory.beginTransaction();
			XMLHibernateDaoFactory.getInstance().getMarcaDAO().update(entity);
			HibernateSessionFactory.commit();
		} catch (Exception e) {
			HibernateSessionFactory.rollback();
			throw e;
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}

	public Marca getMarca(String marCod) throws Exception {
		Marca entity = null;

		try {
			entity = XMLHibernateDaoFactory.getInstance().getMarcaDAO()
			.findById(marCod);
		} catch (Exception e) {
			throw new ZMessManager().new FindingException("Marca");
		} finally {
		}

		return entity;
	}

	public List<Marca> findPageMarca(String sortColumnName,
			boolean sortAscending, int startRow, int maxResults)
			throws Exception {
		List<Marca> entity = null;

		try {
			entity = XMLHibernateDaoFactory.getInstance().getMarcaDAO()
			.findPageMarca(sortColumnName,
					sortAscending, startRow, maxResults);
		} catch (Exception e) {
			throw new ZMessManager().new FindingException("Marca");
		} finally {
		}

		return entity;
	}

	public Long findTotalNumberMarca() throws Exception {
		Long entity = null;

		try {
			entity = XMLHibernateDaoFactory.getInstance().getMarcaDAO()
			.findTotalNumberMarca();
		} catch (Exception e) {
			throw new ZMessManager().new FindingException("Marca Count");
		} finally {
		}

		return entity;
	}

	/**
	 *
	 * @param varibles
	 *            este arreglo debera tener:
	 *
	 * [0] = String variable = (String) varibles[i]; representa como se llama la
	 * variable en el pojo
	 *
	 * [1] = Boolean booVariable = (Boolean) varibles[i + 1]; representa si el
	 * valor necesita o no ''(comillas simples)usado para campos de tipo string
	 *
	 * [2] = Object value = varibles[i + 2]; representa el valor que se va a
	 * buscar en la BD
	 *
	 * [3] = String comparator = (String) varibles[i + 3]; representa que tipo
	 * de busqueda voy a hacer.., ejemplo: where nombre=william o where nombre<>william,
	 * en este campo iria el tipo de comparador que quiero si es = o <>
	 *
	 * Se itera de 4 en 4..., entonces 4 registros del arreglo representan 1
	 * busqueda en un campo, si se ponen mas pues el continuara buscando en lo
	 * que se le ingresen en los otros 4
	 *
	 *
	 * @param variablesBetween
	 *
	 * la diferencia son estas dos posiciones
	 *
	 * [0] = String variable = (String) varibles[j]; la variable ne la BD que va
	 * a ser buscada en un rango
	 *
	 * [1] = Object value = varibles[j + 1]; valor 1 para buscar en un rango
	 *
	 * [2] = Object value2 = varibles[j + 2]; valor 2 para buscar en un rango
	 * ejempolo: a > 1 and a < 5 --> 1 seria value y 5 seria value2
	 *
	 * [3] = String comparator1 = (String) varibles[j + 3]; comparador 1
	 * ejemplo: a comparator1 1 and a < 5
	 *
	 * [4] = String comparator2 = (String) varibles[j + 4]; comparador 2
	 * ejemplo: a comparador1>1  and a comparador2<5  (el original: a > 1 and a <
	 * 5) *
	 * @param variablesBetweenDates(en
	 *            este caso solo para mysql)
	 *  [0] = String variable = (String) varibles[k]; el nombre de la variable que hace referencia a
	 *            una fecha
	 *
	 * [1] = Object object1 = varibles[k + 2]; fecha 1 a comparar(deben ser
	 * dates)
	 *
	 * [2] = Object object2 = varibles[k + 3]; fecha 2 a comparar(deben ser
	 * dates)
	 *
	 * esto hace un between entre las dos fechas.
	 *
	 * @return lista con los objetos que se necesiten
	 * @throws Exception
	 */
	public List<Marca> findByCriteria(Object[] variables,
			Object[] variablesBetween, Object[] variablesBetweenDates)
			throws Exception {
		List<Marca> list = new ArrayList<Marca>();
		String where = new String();
		String tempWhere = new String();

		if (variables != null) {
			for (int i = 0; i < variables.length; i++) {
				if ((variables[i] != null) && (variables[i + 1] != null) &&
						(variables[i + 2] != null) &&
						(variables[i + 3] != null)) {
					String variable = (String) variables[i];
					Boolean booVariable = (Boolean) variables[i + 1];
					Object value = variables[i + 2];
					String comparator = (String) variables[i + 3];

					if (booVariable.booleanValue()) {
						tempWhere = (tempWhere.length() == 0)
						? ("(model." + variable + " " + comparator + " \'" +
								value + "\' )")
								: (tempWhere + " AND (model." + variable + " " +
										comparator + " \'" + value + "\' )");
					} else {
						tempWhere = (tempWhere.length() == 0)
						? ("(model." + variable + " " + comparator + " " +
								value + " )")
								: (tempWhere + " AND (model." + variable + " " +
										comparator + " " + value + " )");
					}
				}

				i = i + 3;
			}
		}

		if (variablesBetween != null) {
			for (int j = 0; j < variablesBetween.length; j++) {
				if ((variablesBetween[j] != null) &&
						(variablesBetween[j + 1] != null) &&
						(variablesBetween[j + 2] != null) &&
						(variablesBetween[j + 3] != null) &&
						(variablesBetween[j + 4] != null)) {
					String variable = (String) variablesBetween[j];
					Object value = variablesBetween[j + 1];
					Object value2 = variablesBetween[j + 2];
					String comparator1 = (String) variablesBetween[j + 3];
					String comparator2 = (String) variablesBetween[j + 4];
					tempWhere = (tempWhere.length() == 0)
					? ("(" + value + " " + comparator1 + " " + variable +
							" and " + variable + " " + comparator2 + " " + value2 +
							" )")
							: (tempWhere + " AND (" + value + " " + comparator1 +
									" " + variable + " and " + variable + " " +
									comparator2 + " " + value2 + " )");
				}

				j = j + 4;
			}
		}

		if (variablesBetweenDates != null) {
			for (int k = 0; k < variablesBetweenDates.length; k++) {
				if ((variablesBetweenDates[k] != null) &&
						(variablesBetweenDates[k + 1] != null) &&
						(variablesBetweenDates[k + 2] != null)) {
					String variable = (String) variablesBetweenDates[k];
					Object object1 = variablesBetweenDates[k + 1];
					Object object2 = variablesBetweenDates[k + 2];
					String value = null;
					String value2 = null;

					try {
						Date date1 = (Date) object1;
						Date date2 = (Date) object2;
						value = Utilities.formatDateWithoutTimeInAStringForBetweenWhere(date1);
						value2 = Utilities.formatDateWithoutTimeInAStringForBetweenWhere(date2);
					} catch (Exception e) {
						list = null;
						throw e;
					}

					tempWhere = (tempWhere.length() == 0)
					? ("(model." + variable + " between \'" + value +
							"\' and \'" + value2 + "\')")
							: (tempWhere + " AND (model." + variable +
									" between \'" + value + "\' and \'" + value2 + "\')");
				}

				k = k + 2;
			}
		}

		if (tempWhere.length() == 0) {
			where = null;
		} else {
			where = "(" + tempWhere + ")";
		}

		try {
			list = XMLHibernateDaoFactory.getInstance().getMarcaDAO()
			.findByCriteria(where);
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		} finally {
		}

		return list;
	}
	public List<Marca> listMarca;
	public List<Marca> consultarMarca (String nombre)throws Exception{
		listMarca = new ArrayList<Marca>();
		MarcaDAO marDao = new MarcaDAO();
		listMarca = (List<Marca>) marDao.consultarMarcaPorTipoVehiculo(nombre);

		return listMarca;
	}
}
